//
//  Advertising ViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/21.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "AdvertisingViewController.h"
#import "WebViewController.h"
@interface Advertising_ViewController ()

@property (nonatomic, strong) UIButton *jumpBtn;//跳过按钮
@property (nonatomic, strong) UIImageView *backgroudImg;

@property (nonatomic, copy) NSString *imgUrl;
@property (nonatomic, copy) NSString *webUrl;


@property (nonatomic, assign) BOOL canJump;// 默认YES


@end

@implementation Advertising_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _canJump = YES;
    _jumpBtn.hidden = YES;
    
    _backgroudImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT)];
    _backgroudImg.userInteractionEnabled = YES;
    [self.view addSubview:_backgroudImg];
    
    
    
    _jumpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_jumpBtn setTitle:@"跳过" forState:0];
    _jumpBtn.titleLabel.font = PFRFONT(12);
    [_jumpBtn setTitleColor:ColorWhite forState:0];
    _jumpBtn.backgroundColor = ColorFrom16A(0x000000, 0.2);//ColorFrom16(0xFEDE6D)
    _jumpBtn.layer.cornerRadius = 8;
    _jumpBtn.layer.masksToBounds = YES;
    _jumpBtn.userInteractionEnabled = YES;
    [_jumpBtn setEnlargeEdge:10];
    [_jumpBtn addTarget:self action:@selector(handleJumpBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_backgroudImg addSubview:_jumpBtn];
    [_jumpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(40);
        make.right.equalTo(self.view).offset(-20);
        make.width.equalTo(@40);
        make.height.equalTo(@20);
    }];
    
    [self startRequestData];
    
}

- (void)handleJumpBtn:(UIButton *)sender
{
    _canJump = YES;
    [self jumpMethod];

}

- (void)startRequestData {
    
    @weakobj(self);
    BaseNetwork *baseService = [BaseNetwork new];
    baseService.interfaceType = InterfaceTypeAD;

    [baseService sendGetRequestURL:[NSString stringWithFormat:@"%@/common/welcomeGet",GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        
        @strongobj(self);
        NSDictionary *dictionary = resultDict[@"data"];
        NSArray *arr = dictionary[@"list"];
        NSLog(@"欢迎页 %@", resultDict);
        //            self.imgUrl = @"http://chuantu.biz/t5/100/1496642143x2890174016.jpg";
        //            self.webUrl = @"http://www.baidu.com";
        //            [self downloadImage];
        
        if (arr.count > 0) {
            NSDictionary *dict = arr[0];
//            
            self.imgUrl = STRING(dict[@"img"]);
            self.webUrl = STRING(dict[@"url"]);
            
            if ([self.imgUrl hasPrefix:@"http"]) {
                [self downloadImage];
            } else {
                [self handleJumpBtn:nil];// 立即返回
            }
            
        } else {
            [self handleJumpBtn:nil];// 立即返回
        }
        
        
    } andFailure:^(NSError *error, NSString *errorMsg) {
        
        [self handleJumpBtn:nil];// 立即返回
    }];
}

- (void)downloadImage {
    
    
        [self.backgroudImg sd_setImageWithURL:[NSURL URLWithString:@"http://chuantu.biz/t5/100/1496642143x2890174016.jpg"]];
    
    self.canJump = YES;
    
    
    [self.backgroudImg sd_setImageWithURL:[NSURL URLWithString:self.imgUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        if (image && !error) {
            
            self.canJump = NO;
            self.jumpBtn.hidden = NO;
            [self performSelector:@selector(countDown) withObject:nil afterDelay:3.0];// 下载完图片5秒退出
            
        } else {
            
            [self handleJumpBtn:nil];// 立即返回
        }
    }];
    
    [self performSelector:@selector(jumpMethod) withObject:nil afterDelay:2.0];// 2秒下载图片失败直接退出
    
}

- (void)countDown {
    
    _canJump = YES;
    [self jumpMethod];
   
}

- (void)jumpMethod {
    
    [self performSelector:@selector(delayAction) withObject:nil afterDelay:0.5];
    if (!_canJump) {
        return;
    }
    
    NSString *appVersion = [[NSUserDefaults standardUserDefaults]objectForKey:kUDAppVersion];
    if ([appVersion isEqualToString:APP_VERSION]) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.view.alpha = 0.0f;
        
    } completion:^(BOOL finished) {
        
        [self.view removeFromSuperview];
    }];
//    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)delayAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alert" object:nil];

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(self.webUrl.length == 0)
    {
        return;
    }
    NSLog(@"哈哈哈 %@", self.webUrl);
    NSString *webUrl = self.webUrl;//@"http://www.baidu.com";
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotiADClick object:webUrl];
    [self handleJumpBtn:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
